//
//  stackImp.c
//  Chapter_1
//
//  Created by hao on 18/3/21.
//  Copyright © 2018年 hao. All rights reserved.
//

#include "stackImp.h"

// 创建一个栈链表
StackList createStack()
{
    StackList stack = (StackList)malloc(sizeof(struct SinglyLinkedNode));
    stack->next = TPL_LIST_NULL;
    return stack;
}

int isEmptyInStack(StackList stack)
{
    if (stack->next == TPL_LIST_NULL) {
        return TPL_FALSE;
    }
    return TPL_TRUE;
}

// 将值押入栈顶
void pushStackList(ElementType x, StackList stack)
{
    if (stack == TPL_LIST_NULL) {
        printf("插入栈为空 \n");
        return ;
    }
    StackList insertS = createStack();
    insertS->data = x;
    insertS->next = stack->next;
    // 将stack作为head
    stack->next = insertS;
}

// 拿到栈顶的值，并移出链表
// 第二种方式是把stack->next作为栈顶
ElementType popStackList(StackList stack)
{
    if (stack->next == TPL_LIST_NULL) {
        return TPL_NOT_FOUND;
    }
    StackList resultS = stack->next;
    ElementType res = resultS->data;
    stack->next = resultS->next;
    free(resultS);
//    printf("resultS = %p, stack = %p \n", resultS, stack);
    return res;
}

// 把stack作为栈顶
ElementType TestPopStackList(StackList *stack)
{
    if (*stack == TPL_LIST_NULL) {
        return TPL_NOT_FOUND;
    }
    StackList resultS = *stack;
    ElementType res = resultS->data;
    /// 函数内部已经指向下一个节点，为什么外部不同步？因为修改值就必须传地址，C语言传参数是值传递
    *stack = resultS->next;
    free(resultS);
    printf("resultS = %p, stack = %p \n", resultS, *stack);
    return res;
}

